package com.secsys.service.impl;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.secsys.dto.BbsPostDTO;
import com.secsys.model.TbBbsModule;
import com.secsys.model.TbBbsPost;
import com.secsys.model.TbBbsReply;
import com.secsys.model.TbSysUser;
import com.secsys.service.PostService;
import com.secsys.util.DateFormatUtils;

/**
 * @Description 帖子业务逻辑接口实现类
 * @author LiusQ
 * @Date 2011-4-8 20:33
 */
public class PostServiceImpl extends ServiceImpl<TbBbsPost, Integer> implements
		PostService {

	@Override
	public boolean auditPost(TbBbsPost post) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public void deletePost(TbBbsPost post) {
		// TODO Auto-generated method stub

	}

	/**
	 * 
	 * @Description 通过模块ID查的对应模块下的帖子数
	 * @param tbBbsModule
	 * @return
	 */
	public List<BbsPostDTO> getAllPost(TbBbsModule tbBbsModule) {
		// TODO Auto-generated method stub
		String hql = "from TbBbsPost post where post.tbBbsModule=?";
		List<TbBbsPost> allPost = this.dao.find(hql,
				new Object[] { tbBbsModule });
		List<BbsPostDTO> conList = null;
		if (allPost != null && allPost.size() != 0) {
			conList = new ArrayList<BbsPostDTO>();
			forEach(allPost, conList);
		}
		return conList;
	}

	/**
	 * @Description 用户发布帖子
	 * @param post
	 * @return void
	 */
	public void publishPost(TbBbsPost post) {
		// TODO Auto-generated method stub
		this.dao.save(post);
	}

	/**
	 * 
	 * @Description 将postDto转换成post的pojo
	 * @param bbsPostDTO
	 * @return
	 */
	public TbBbsPost postBeanFromDTO(BbsPostDTO bbsPostDTO) {
		TbBbsPost post = new TbBbsPost();
		post.setTitle(bbsPostDTO.getTitle());
		post.setContent(bbsPostDTO.getContent());
		post.setStatue(bbsPostDTO.getStatue());
		 
	 
		return post;

	}

	@Override
	public List<TbBbsPost> queryPostByModStatue(String module, String statue) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void savePost(TbBbsPost post) {
		// TODO Auto-generated method stub

	}

	/**
	 * @Description 更新帖子
	 */
	@Override
	public void updatePost(TbBbsPost post) {
		// TODO Auto-generated method stub
		this.dao.update(post);
	}

	/**
	 * @Description 获取帖子的基本信息
	 * @param id
	 * @return
	 */
	public BbsPostDTO queryPostById(Integer id) {

		BbsPostDTO postDTO = null;
		TbBbsPost post = this.findById(id);
     
		if (post != null) {
			postDTO = new BbsPostDTO();
			postDTO.setId(post.getId());
			postDTO.setTitle(post.getTitle());
			postDTO.setContent(post.getContent());
			postDTO.setStatue(post.getStatue());
			postDTO.setPublishTime(DateFormatUtils.convertDateTimeToString(post.getPublishTime()));
			postDTO.setAuthor(post.getTbSysUser().getUserName());
			postDTO.setAutorId(post.getTbSysUser().getId());
			postDTO.setViews(post.getViews());
			postDTO.setReplyNum(post.getReplyNum());
            System.out.println(post.getTbSysUser().getId()+"*****************");
            postDTO.setLocalModule(post.getTbBbsModule().getModuleName());
               String code=   post.getTbBbsModule().getParent();  //
               postDTO.setParentModuleCode(code);
           
			if (post.getIsDigest() != null)
				postDTO.setIsDigest(post.getIsDigest()); // 设置为精华
			if (post.getIsTop() != null)
				postDTO.setIsTop(post.getIsTop()); // 设置为置顶

		}
		return postDTO;
	}

	/**
	 * 
	 * @Description 查找对应的帖子及回复信息
	 * @param id
	 *            帖子ID
	 * @param replyService
	 * @return
	 */
	public List<BbsPostDTO> queryPostListInfo(TbBbsModule tbBbsModule,
			ReplyServiceImpl replyService) {
		String hql = "from TbBbsPost post where post.tbBbsModule=?";
		List<TbBbsPost> allPost = this.dao.find(hql,
				new Object[] { tbBbsModule });
		List<BbsPostDTO> conList = null;
		if (allPost != null && allPost.size() != 0) {
			conList = new ArrayList<BbsPostDTO>();
			forEach(allPost, conList,replyService);
		}
		return conList;
		 
	}
	/**
	 * 
	 * @Description 通过用户ID查询该用户的发帖数 
	 * @param user
	 * @return
	 */
    public List<BbsPostDTO> queryPostListInfoByAuthor(TbSysUser user){
    	 String hql="from TbBbsPost post where post.tbSysUser=? order by post.lastReplyTime DESC";
    	 List<TbBbsPost> allPost=dao.find(hql,new Object[]{user});
    	 List<BbsPostDTO> conList=null;
    	 if(allPost!=null&&allPost.size()!=0){
    		 conList=new ArrayList<BbsPostDTO>();
    		 forEach(allPost, conList);
    	 }
    	 return conList;
    }
	/**
	 * 
	 * @Description 将TbBbsPost 集合转换成BbsPostDTO集合
	 * @param list
	 * @param conList
	 */
	private void forEach(List<TbBbsPost> list, List<BbsPostDTO> conList) {
		BbsPostDTO bbsPostDTO = null;
		for (TbBbsPost tbBbsPost : list) {
			bbsPostDTO = new BbsPostDTO();
			bbsPostDTO.setId(tbBbsPost.getId());
			bbsPostDTO.setTitle(tbBbsPost.getTitle());
			 
			bbsPostDTO.setPublishTime(DateFormatUtils.convertDateTimeToString(tbBbsPost.getPublishTime()));
			bbsPostDTO.setContent(tbBbsPost.getContent());
			bbsPostDTO.setViews(tbBbsPost.getViews());
			bbsPostDTO.setReplyNum(tbBbsPost.getReplyNum());
			bbsPostDTO.setAutorId(tbBbsPost.getTbSysUser().getId());
			bbsPostDTO.setAuthor(tbBbsPost.getTbSysUser().getUserName());
			bbsPostDTO.setLastReplyTime(DateFormatUtils.convertDateTimeToString(tbBbsPost.getLastReplyTime()));
			bbsPostDTO.setModuleName(tbBbsPost.getTbBbsModule().getModuleName());
			bbsPostDTO.setStatue(tbBbsPost.getStatue());
			conList.add(bbsPostDTO);
		}
	}

	private void forEach(List<TbBbsPost> list, List<BbsPostDTO> conList,
			ReplyServiceImpl replyService) {
		BbsPostDTO bbsPostDTO = null;
		for (TbBbsPost tbBbsPost : list) {
			bbsPostDTO = new BbsPostDTO();
			bbsPostDTO.setId(tbBbsPost.getId());
			bbsPostDTO.setTitle(tbBbsPost.getTitle());
			bbsPostDTO.setPublishTime(DateFormatUtils.convertDateTimeToString(tbBbsPost.getPublishTime()));
			bbsPostDTO.setContent(tbBbsPost.getContent());
			bbsPostDTO.setViews(tbBbsPost.getViews());
			bbsPostDTO.setReplyNum(tbBbsPost.getReplyNum());
			bbsPostDTO.setAutorId(tbBbsPost.getTbSysUser().getId());
			bbsPostDTO.setAuthor(tbBbsPost.getTbSysUser().getUserName());
			 
			TbBbsReply replyTemp = replyService.queryReplyByPostId(
					tbBbsPost,tbBbsPost.getLastReplyTime());
			if(replyTemp!=null){
			bbsPostDTO.setReplyAuthorName(replyTemp.getTbSysUser().getUserName());
			bbsPostDTO.setReplyTitle(replyTemp.getTitle());
			}
			bbsPostDTO.setLastReplyTime(DateFormatUtils.convertDateTimeToString(tbBbsPost.getLastReplyTime()));
			conList.add(bbsPostDTO);
		}
	}
  
	
	/**
	 * 
	 * @Description  通过模块Id,状态查询帖子数,最后回帖时间
	 */
	public TbBbsPost queryPostByModuleCode(Integer moduleId){
		String hql="from TbBbsPost post where post.tbBbsModule.id=?  order by post.lastReplyTime DESC";
		List postList=dao.find(hql, new Object[]{moduleId});
		return postList!=null&&postList.size()>0? (TbBbsPost)postList.get(0):null;
	}
	
	public List queryPostByModuleId(Integer moduleId){
		String hql="from TbBbsPost post where post.tbBbsModule.id=?  order by post.lastReplyTime DESC";
		List postList=dao.find(hql, new Object[]{moduleId});
		return postList!=null&&postList.size()>0? postList:null;
	}
	
	
	/**
	 * 
	 * @Description  查询日期查询帖子数,并按照指定的顺序查询 
	 * @return
	 */
	public  List  queryPostByDate(Date startdate,Date endDate,int moduleId){
		  String hql="from TbBbsPost post where post.tbBbsModule.id=? and post.publishTime  between ? and ?  ";
		  List   dayPostList=dao.find(hql, new Object[]{moduleId,startdate,endDate});
		  return dayPostList!=null&&dayPostList.size()>0?dayPostList:null;
	}
	
	
	
	/**
	 * @Description 更新或保存帖子
	 */
	@Override
	public void saveOrUpdate(TbBbsPost entity) {
		// TODO Auto-generated method stub
		super.saveOrUpdate(entity);
	}
	 /**
	  * 
	  * @Description  通过用户ID查看此用户精华帖子数 
	  * @param id
	  * @return
	  */
   public Integer getDigestCount(Integer userId,boolean isDigest){
	   String hql="from TbBbsPost post where post.tbSysUser.id=? and post.isDigest=?";
	  List resultList= this.dao.find(hql, new Object[]{userId,isDigest});
	   return resultList!=null&&resultList.size()>0?(Integer)resultList.size():0;
   }
   
   /**
    * 
    * @Description  获取某时间段论坛发帖情况
    * @param startDate
    * @param endDate
    * @return
    */
   public Integer totalCountPostByDate(Date startDate,Date endDate){
		String hql="select count(*) from TbBbsPost post where  post.publishTime  between ? and ?  ";
	    List list= dao.find(hql, new Object[]{startDate,endDate});
	    return list!=null&&list.size()>0?((Long)list.get(0)).intValue():0;
	}
   
   /**
    * 
    * @Description  获取某时间段论坛模块module发帖情况
    * @param startDate
    * @param endDate
    * @return
    */
   public Integer totalCountPostByModuleAndDate(Date startDate,Date endDate,String parent){
		String hql="select count(*) from TbBbsPost post where post.tbBbsModule.parent =? and  post.publishTime  between ? and ?  ";
	    List list= dao.find(hql, new Object[]{parent,startDate,endDate});
	    return list!=null&&list.size()>0?((Long)list.get(0)).intValue():0;
	}
   
   /**
    * 
    * @Description  历史每天最高发帖量 
    * @return
    */
   public int totalMaxPostCount(){
	          String sql="select max(tm.total)  dayMaxCount from( select count(*) total from  (SELECT  DATE_FORMAT(publish_time,'%Y-%m-%d') dateName, id FROM tb_bbs_post t) t1,tb_bbs_post t2 where t1.id=t2.id group by t1.dateName) tm;";
	        List list= dao.getCount(sql);
	        return  list!=null&&list.size()>0?((BigInteger)list.get(0)).intValue():0;
   }
   
   
   /**
    * 
    * @Description 统计不同模块下 历史每天最高发帖量 
    * @return
    */
   public int totalMaxPostCountByModuleId(String hql,String moduleCode){
	  List listTest= totalPostCountByParentModuleCode(moduleCode);
	  List list=null;
	  if(listTest!=null){
       String sql="select max(tm.total)  dayMaxCount from( select count(*) total from  (SELECT  DATE_FORMAT(publish_time,'%Y-%m-%d') dateName, id FROM tb_bbs_post t) t1,tb_bbs_post t2 where t1.id=t2.id and t2.local_module_id "+hql+" group by t1.dateName) tm";
        list= dao.getCount(sql);
	    }
     return  list!=null&&list.size()>0?((BigInteger)list.get(0)).intValue():0;
   }
   
   /**
    * 
    * @Description 通过父模块查询帖子总数 
    * @param parentCode
    * @return
    */
   public List totalPostCountByParentModuleCode(String parentCode){
	   String sql="from TbBbsPost post where post.tbBbsModule.parent=?  ";
	    List list=dao.find(sql, new Object[]{parentCode});
	    return list!=null&&list.size()>0?list:null;
   }
   
   
   /**
    * 
    * @Description 屏蔽帖子  
    * @param post
    */
   public void noShowPostCotent(TbBbsPost post){
	        dao.update(post);
	   
   }
   
   /**
    * 
    * @Description 论坛所有发帖量
    * @return
    */
   public Integer allPostCount(){
	     return dao.count();
	   
   }
   
}
